<template>
  <div
    class="uploader"
    :class="{ dragging: isDragging}"
    @dragenter="onDragEnter"
    @dragleave="onDragLeave"
    @dragover.prevent
    @drag="onDrap"
  >
    <div v-show="!images.length">
      <i class="fa fa-cloud-upload"></i>
      <p>Drag your images here</p>
      <div>OR</div>
      <div class="file-input">
        <label for="file">Select a file</label>
        <input
          id="file"
          type="file"
          multiple
          @change="onInputChange"
        >
      </div>
    </div>
    <div v-show="images.length" class="images-preview">
      <div v-for="(image ,index) in images" :key="index" class="img-wrapper">
        <img :src="image" :alt="`Image Uploader ${index}`">
        <div class="details">
          <span class="name" v-text="file[index].name"></span>
          <span class="size" v-text="file[index].size"></span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isDragging: false,
      dragCount: 0,
      files: [],
      images: []
    }
  },
  methods: {
    onInputChange(e) {
      const files = e.target.files
      Array.from(files).forEach(file => this.addImage(file))
    },
    onDragEnter(e) {
      e.preventDefault()
      this.dragCount++
      this.isDragging = true
    },
    onDragLeave(e) {
      e.preventDefault()
      this.dragCount--
      if(this.dragCount <=0) {
        this.isDragging = false
      }
    },
    onDrap(e) {
      e.preventDefault()
      e.stopPropagation()
      this.isDragging = false
      const files = e.dataTransfer.files
      Array.from(files).forEach(file => this.addImage(file))
    },
    addImage(file) {
      // if(file.type.match('img.*')) {
      //   console.log(`${file.name} is not image`)
      //   return
      // }
      this.push(file)
      const img = new Image()
      const reader = new FileReader()
      reader.onload = e => this.images.push(e.target.result)
      reder.readAsDataURL(file)
      console.log(img)
    }
  }
}
</script>

<style lang="scss" scoped>
 .uploader {
   width: 500px;
   background-color: #2196F3;
   color: #fff;
   padding: 40px 15px;
   text-align: center;
   border-radius: 10px;
   border: 3px dashed #fff;
   font-size: 20px;
   position: relative;
   &.dragging {
     background-color: #fff;
     color: #2196F3;
     border: 3px dashed #2196F3;
     .file-input label {
       background-color: #fff;
       color: #2196F3;
     }
   }
   i {
   font-size: 85px;
  }
  label,input {
    background-color: #fff;
    color: #2196F3;
    width: 300px;
    position: absolute;
    left: 100px;
    bottom: 5px;
    border-radius: 4px;
    margin-top: 7px;
    cursor: pointer;
  }
  input {
    opacity: 0;
    z-index: -2;
  }
}



</style>
